﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace EPPLog
{
    public static class Logger
    {
        public static void Info(string format, params object[] args)
        {
            DoLog("Info", args.Length == 0 ? format : string.Format(format, args));
        }
        public static void Info(Exception exception)
        {
            Info(ExceptionInfo(exception));
        }

        public static void Debug(string format, params object[] args)
        {
            DoLog("Debug", args.Length == 0 ? format : string.Format(format, args));
        }
        public static void Debug(Exception exception)
        {
            Debug(ExceptionInfo(exception));
        }
        

        public static void Error(string format, params object[] args)
        {
            DoLog("Error", args.Length == 0 ? format : string.Format(format, args));
        }

        public static void Error(Exception exception)
        {
            Error(ExceptionInfo(exception));
        }

        static string EPPLogPath = "";
        static object EPPLogLock = new object();

        public static void SetPath(string path)
        {
            EPPLogPath = path;
            if (!Directory.Exists(EPPLogPath))
                Directory.CreateDirectory(EPPLogPath);
        }
        
        static void DoLog(string _type, string message)
        {
            lock (EPPLogLock)
            {
                if (EPPLogPath == "")
                    return;

                FileStream fs = null;
                try
                {
                    string fullname = EPPLogPath + (_type == "Error" ? "warning_" : "") + DateTime.Now.ToString("yyyyMMdd") + ".txt";                   
                    fs = new FileStream(fullname, FileMode.Append);
                    string content = string.Format("{0}: [{1}] {2}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), _type, message);
                    byte[] buffer = Encoding.UTF8.GetBytes(content);
                    fs.Write(buffer, 0, buffer.Length);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Flush();
                        fs.Close();
                        fs = null;
                    }
                }
            }
        }
        

        public static string ExceptionInfo(Exception ex)
        {
            string e1 = String.Format("Exception: {0}\r\nMessage: {1}\r\nStack: {2}", ex.GetType().Name, ex.Message, ex.StackTrace);
            string e2 = "";
            if (ex.InnerException != null)
                e2 = String.Format("\r\nException: {0}\r\nMessage: {1}\r\nStack: {2}", ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
            return e1 + e2;
        }
        
    }

}
